package pe.com.cineplanet.dao.impl;

import java.util.List;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

import pe.com.cineplanet.bean.Articulo;
import pe.com.cineplanet.dao.ArticuloDAO;
import pe.com.cineplanet.dao.mapper.ArticuloMapper;

public class ArticuloImpl implements ArticuloDAO {

	
	protected JdbcTemplate jdbcTemplate;
	
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	

	public Articulo select(String codarticulo) {
		StringBuffer strQuery= new StringBuffer();
		strQuery.append("SELECT a.id_articulo, r.id_rubro, r.descrip as descripRubro, a.descrip as descripArticulo, a.precio FROM articulos a ");
		strQuery.append("INNER JOIN rubros r on a.id_rubro = r.id_rubro ");
		strQuery.append("WHERE a.id_articulo = ? ");
	
		Object[] params = new Object[]{
				codarticulo
		};
		
		try {
			return (Articulo)jdbcTemplate.queryForObject(strQuery.toString(), params, new ArticuloMapper());
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
		
	}

	@SuppressWarnings("unchecked")
	public List<Articulo> selectList(String descrip) {
		StringBuffer strQuery= new StringBuffer();
		strQuery.append("SELECT a.id_articulo, r.id_rubro, r.descrip as descripRubro, a.descrip as descripArticulo, a.precio FROM articulos a ");
		strQuery.append("INNER JOIN rubros r on a.id_rubro = r.id_rubro ");
		strQuery.append("WHERE a.descrip like ? ");
	
		Object[] params = new Object[]{
				"%" + descrip + "%"
		};
		

		return jdbcTemplate.query(strQuery.toString(), params, new ArticuloMapper());
		

	}
	
	public void update(Articulo articulo){
		StringBuffer strExecute = new StringBuffer();
		strExecute.append("UPDATE articulos SET id_rubro=?, descrip=?, precio=? ");
		strExecute.append("WHERE id_articulo = ? ");
	
		Object[] params = new Object[]{
				articulo.getRubro().getIdrubro(),
				articulo.getDescrip(),
				articulo.getPrecio(),
				articulo.getIdarticulo()
				
		};
		
		jdbcTemplate.update(strExecute.toString(), params);
	}
	
	
	public void delete(Articulo articulo){
		StringBuffer strExecute = new StringBuffer();
		strExecute.append("DELETE FROM articulos ");
		strExecute.append("WHERE id_articulo = ? ");
	
		Object[] params = new Object[]{
				articulo.getIdarticulo()
				
		};
		
		jdbcTemplate.update(strExecute.toString(), params);
	}
	
}
